import requests
import os
import sys
import json
import re
import base64

def search_file(path, name):
    cwd = os.getcwd()
    for filename in os.listdir(path):
        fp = os.path.join(path, filename)
        if os.path.isfile(fp) and filename == name:
            return fp
        elif os.path.isdir(fp):
            search_file(fp, name)

    return ''

def upload_md_to_memos(file_name):
    # Memos服务器配置
    API_URL = "http://192.168.0.11:5230/api/v1/memos"  # 替换为实际Memos地址
    API_RES_URL = "http://192.168.0.11:5230/api/v1/resources"  # 替换为实际Memos地址
    API_KEY = "Bearer eyJhbGciOiJIUzI1NiIsImtpZCI6InYxIiwidHlwIjoiSldUIn0.eyJuYW1lIjoiaGl0bW9vbiIsImlzcyI6Im1lbW9zIiwic3ViIjoiMSIsImF1ZCI6WyJ1c2VyLmFjY2Vzcy10b2tlbiJdLCJpYXQiOjE3NDUyMjY5NDl9.Tf-22HwGAkB-AKsOzZ_HB6Jwu2ht0cjvqFkmwnw3vko"                # 替换为你的API密钥
    
    # 检查文件存在性及扩展名
    if not os.path.exists(file_name):
        print(f"错误：文件 '{file_name}' 不存在")
        return
    if not file_name.lower().endswith('.md'):
        print("警告：非Markdown文件，可能无法正确解析")
    
    # 读取文件内容
    try:
        with open(file_name, 'r', encoding='utf-8') as f:
            content = f.read()
    except Exception as e:
        print(f"读取文件失败：{str(e)}")
        return

    # 如果没有标题，添加标题
    match = re.search('^ *# [^#]+', content)
    if match == None:
        title = os.path.basename(file_name)[0:-3] 
        content = f'# {title}\n\n{content}'

    pattern = r'!\[\[([^\]]+)\]\]'
    
    matches = re.finditer(pattern, content)
    files = []
    for match in matches:
        res = match.group(1)
        filepath = search_file(os.getcwd(), res)
        files.append(filepath)

    memo_content = re.sub(pattern, '', content)

    resources = []
    # upload resources
    for f in files:
        print(f'uploading {f}') 
    
        filename = os.path.basename(f)
        ext = os.path.splitext(f)[-1][1:]
        type_str = f"image/{ext}"
        size = os.path.getsize(f)
        fp = open(f, 'rb')
        cont = fp.read()
        fp.close()

        res = {
            "filename": filename,
            "content": base64.b64encode(cont).decode('utf-8'),
            "externalLink": "",
            "type": type_str,
            "size": size,
        }

        headers = {
            "Authorization": API_KEY,
            "Content-Type": "text/plain;charset=UTF-8"
        }

        try:
            response = requests.post(API_RES_URL, json=res, headers=headers)
            if response.status_code == 200:
                print(f"✅ 文件 '{f}' 已成功上传")
                print(f"响应数据：{json.dumps(response.json(), indent=2)}")
                resources.append(response.json())
            else:
                print(f"❌ 上传失败（状态码 {response.status_code}）")
                print(f"错误详情：{response.text}")
        except requests.exceptions.RequestException as e:
            print(f"网络请求异常：{str(e)}")

    # 构建请求
    headers = {
        "Authorization": API_KEY,
        "Content-Type": "text/plain;charset=UTF-8"
    }
    payload = {
        "content": memo_content,
        "visibility": "PUBLIC",  # 可选：PUBLIC/PROTECTED/PRIVATE
        "state": "NORMAL",
        "resources": resources
    }

    # 发送请求
    try:
        response = requests.post(API_URL, json=payload, headers=headers)
        if response.status_code == 200:
            print(f"✅ 文件 '{file_name}' 已成功上传")
            print(f"响应数据：{json.dumps(response.json(), indent=2)}")
        else:
            print(f"❌ 上传失败（状态码 {response.status_code}）")
            print(f"错误详情：{response.text}")
    except requests.exceptions.RequestException as e:
        print(f"网络请求异常：{str(e)}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("用法：python upload_md.py <filename.md>")
        sys.exit(1)
    upload_md_to_memos(sys.argv[1])
